import { computed, inject, reactive } from "vue";
import { loginApi } from "@/api/login";
import { OUT_TOKEN_TIME } from "@/config/login";
import router from "@/router/index";

const useLogin = () => {
  const userInfo = reactive({
    userName: "",
    password: "",
  });
  const tokenInfo = reactive({
    token: null,
    time: Date.now(),
  });

  const login = async () => {
    console.log("login", userInfo);
    try {
      const res = await loginApi(userInfo);
      rememberToken(res);
      router.push({ path: "/" });
    } catch (err) {
      console.log("ServerError", err);
    }
  };

  const rememberToken = (newTokenInfo) => {
    const { token, time } = newTokenInfo;
    tokenInfo.token = token;
    tokenInfo.time = time;

    localStorage.setItem("token", token)
  };

  /**
   * 是否登录
   */
  const isLogin = computed(() => {
    const hasToken = tokenInfo.token;
    const noOutTime = (Date.now() - tokenInfo.time < OUT_TOKEN_TIME)

    return (hasToken && noOutTime)
  });

  const outLogin = () => {
    clearUser()
  };

  const clearUser = () => {
    tokenInfo.time = null
    tokenInfo.token = null
  };

  const getToken = computed(() => {
    return tokenInfo.token
  }) 

  return {
    userInfo,
    tokenInfo,
    isLogin,
    login,
    outLogin,
    getToken
  };
};

export default useLogin;
